package com.njupt.LinkTable;

/**
 * 203. 移除链表元素
 *
 */
public class RemoveElements {


    /**
     * 不带头节点的单链表
     * 当前遍历的节点指向要判断的节点的前一个
     * @param head  head只想第一个元素
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        //表头节点单独处理
        if(head == null){
            return head;
        }
        ListNode p = head;
        while(p.val == val){
            head = head.next;
            p = head;
            if(p==null){
                return p;
            }
        }

        while(p!= null){
            if(p.next!=null){
                if(p.next.val == val){
                    p.next = p.next.next;
                }

            }
            p = p.next;

        }
        return head;
    }

    /**
     * 这里先采用带头指针和头节点的单链表
     * p遍历的节点是当前要判断的节点，这时候需要一个前指针
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements1(ListNode head, int val) {

        ListNode HEAD = new ListNode(-1, head);

        ListNode pre = HEAD;
        ListNode p = head;
        while(p!=null){
            if(p.val == val){
                pre.next = p.next;
                p = p.next;
            }else {
                pre = p;
                p = p.next;
            }

        }
        return HEAD.next;
    }

    public  void printList(ListNode head){
        ListNode p = head;
        while(p != null){
            System.out.print(p.val + " ");
            p = p.next;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(1);
        ListNode node4 = new ListNode(1);
        ListNode node5 = new ListNode(1);
        ListNode node6 = new ListNode(1);
        head.next = node1; node1.next = node2;node2.next = node3;
//        node3.next = node4; node4.next = node5; node5.next = node6;

        RemoveElements test = new RemoveElements();
        ListNode listNode = test.removeElements1(head, 2);
        test.printList(listNode);


    }
}
